package cn.unknowpupil.init.controller.system;


import cn.unknowpupil.init.common.constant.CacheKeyConstants;
import cn.unknowpupil.init.common.constant.SecurityConstants;
import cn.unknowpupil.init.common.enums.BusinessType;
import cn.unknowpupil.init.common.resopnse.ResultResponse;
import cn.unknowpupil.init.components.annotation.Log;
import cn.unknowpupil.init.components.annotation.RepeatSubmit;
import cn.unknowpupil.init.domain.system.SysRole;
import cn.unknowpupil.init.service.system.ISysRoleService;
import cn.unknowpupil.init.utils.redis.RedisUtils;
import cn.unknowpupil.init.utils.strings.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created at 2020-10-21 by  w10g <br>
 * Initialize SysRole  ... <br>
 * 角色信息表 视图浏览层处理
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Api(tags = {"系统-角色信息表模块"}, value = "SysRole")
@RestController
@RequestMapping(value = "admin/sys-role")
public class SysRoleController {

    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private ISysRoleService SysRoleService;



    /**
     * 新增
     *
     * @param SysRole {@link SysRole}  角色信息表
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：新增")
    @RepeatSubmit
    @Log(title = "新增角色", businessType = BusinessType.INSERT)
    @PreAuthorize("@ps.hasPerm('system:role:create')")
    @PostMapping("create")
    public ResultResponse create(@Validated @RequestBody SysRole SysRole) {
        redisUtils.del(CacheKeyConstants.ROLE_KEY);
        // 业务逻辑
        boolean created = SysRoleService.create(SysRole);
        if (created) {
            return ResultResponse.success("创建成功");
        } else {
            return ResultResponse.buildFailure("创建失败");
        }

    }

    /**
     * 修改
     *
     * @param role {@link SysRole}  角色信息表
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：修改")
    @RepeatSubmit
    @Log(title = "修改角色", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ps.hasPerm('system:role:update')")
    @PutMapping("update")
    public ResultResponse update(@Validated @RequestBody SysRole role) {
        redisUtils.del(CacheKeyConstants.ROLE_KEY);
        SysRoleService.checkRoleAllowed(role);
        // 业务逻辑
        boolean update = SysRoleService.update(role);
        if (update) {
            return ResultResponse.success("修改成功");
        } else {
            return ResultResponse.buildFailure("修改角色'" + role.getName() + "'失败，请联系管理员");
        }

    }


    /**
     * 获取
     *
     * @param SysRoleId {@code Long}
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：获取")

    @GetMapping("get/{SysRoleId}")
    public ResultResponse get(@PathVariable("SysRoleId") Long SysRoleId) {
        SysRole SysRole = SysRoleService.info(SysRoleId);
        return ResultResponse.buildSuccess(SysRole);
    }

    @ApiOperation("系统：状态修改")
    @RepeatSubmit
    @Log(title = "修改角色状态", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ps.hasPerm('system:role:update')")
    @PutMapping("change/status")
    public ResultResponse changeStatus(@RequestBody SysRole role) {
        redisUtils.del(CacheKeyConstants.ROLE_KEY);
        SysRoleService.checkRoleAllowed(role);
        boolean b = SysRoleService.updateById(role);
        if (b) {
            return ResultResponse.success("成功");
        } else {
            return ResultResponse.buildFailure();
        }
    }


    /**
     * 删除
     *
     * @param ids {@code Long}
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：删除")
    @RepeatSubmit
    @Log(title = "删除角色", businessType = BusinessType.DELETE)
    @PreAuthorize("@ps.hasPerm('system:role:delete')")
    @DeleteMapping("remove/{ids}")
    public ResultResponse remove(@PathVariable("ids") Long[] ids) {
        redisUtils.del(CacheKeyConstants.ROLE_KEY);
        // 业务逻辑
        boolean deleted = SysRoleService.delete(ids);
        if (deleted) {
            return ResultResponse.success("删除成功");
        } else {
            return ResultResponse.buildFailure("删除失败");
        }
    }

    /**
     * 分页
     *
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：分页")
    @GetMapping("page/{current}/{size}")
    public ResultResponse<IPage<SysRole>> page(@PathVariable("current") int current, @PathVariable("size") int size, @ModelAttribute SysRole SysRole) {
        IPage<SysRole> list = SysRoleService.page(current,size,SysRole);
        return ResultResponse.buildSuccess(list);
    }

    @ApiOperation("系统：获取角色选择框列表")
    @GetMapping("/option/select/{id}")
    public ResultResponse optionSelect(@PathVariable Long id) {

        Long roleId = SysRoleService.selectRoleByUserId(id);
        Map<String,Object> result = Maps.newHashMap();
        result.put("checkedKey",roleId);
        Object roles = redisUtils.get(CacheKeyConstants.ROLE_KEY);
        if(StringUtils.isNull(roles)){
            List<SysRole> list = SysRoleService.list(new LambdaQueryWrapper<SysRole>().eq(SysRole::getStatus,0));
            boolean set = redisUtils.set(CacheKeyConstants.ROLE_KEY, list);
            result.put("roles",list);
            return ResultResponse.buildSuccess(result);
        }else {
            List<SysRole> sysRoles = StringUtils.cast(roles);
            result.put("roles",sysRoles);
            return ResultResponse.buildSuccess(result);
        }
    }


}
